<template>
  <div>
    <div class="headPart">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="showParameter">选择参数</el-button>
        </el-form-item>
        <el-form-item>
          <el-date-picker
              v-model="timeRange"
              type="daterange"
              :picker-options="pickerOptions"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy年MM月dd日"
              value-format="yyyy-MM-dd"
              align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="success"
                     @click="confirmPrint"
                     v-loading.fullscreen.lock="isLoading"
                     element-loading-background="rgba(0, 0, 0, 0.8)"
                     element-loading-spinner="el-icon-loading"
                     element-loading-text="拼命渲染中(ง •̀_•́)ง"
          >确定查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="chartPart">
      <div id="line" style="height: calc(100vh - 210px); width: calc(100% - 50px);"></div>
    </div>
    <el-dialog :visible.sync="DialogTimePick" title="选择呈现参数">
      <el-transfer
          style="text-align: left; display: inline-block;"
          v-model="ShowParam"
          filterable
          filter-placeholder="请输入要呈现的参数"
          :titles="['可选参数', '呈现参数']"
          :button-texts="['排除', '选中']"
          :data="ParamData">
      </el-transfer>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "parallelComp",
  data() {
    return {
      isLoading: false,
      DialogTimePick: false,
      chartSideWall: null,
      optionsSideWall: null,
      timeRange:[],
      ShowParam: ['1001'],
      ParamData:[
        {
          label: '炉喉温度℃',
          key: '1'
        },
        {
          label: '炉腹温度℃',
          key: '2'
        },
        {
          label: '铁水温度℃',
          key: '3'
        },
        {
          label: '铁水压力MPa',
          key: '4'
        },
        {
          label: '铁水流量kg/s',
          key: '5'
        },
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    determineScalingFactor(maxValue) {
      if (maxValue === 0) return 1;
      const exponent = Math.log10(maxValue);
      const scale = Math.pow(10, Math.floor(exponent));
      return maxValue / scale > 10 ? scale * 10 : scale;
    },

    getMaxDecimalPlaces(data) {
      return Math.max(...data.map(v => {
        const decimalPart = v.toString().split(".")[1];
        return decimalPart ? decimalPart.length : 0;
      }));
    },

    scaleSeriesData(seriesData) {
      const scaledSeries = {};

      for (const label in seriesData) {
        const data = seriesData[label];
        const maxVal = Math.max(...data.map(v => Math.abs(v)));
        const scale = this.determineScalingFactor(maxVal);
        const decimalPlaces = scale === 1 ? this.getMaxDecimalPlaces(data) : Math.max(0, Math.floor(Math.log10(scale)));
        const newLabel = scale !== 1 ? `${label}/${scale}` : label;
        const scaledData = data.map(v => (v / scale).toFixed(decimalPlaces));
        scaledSeries[newLabel] = scaledData.map(Number);
      }

      return scaledSeries;
    },

    updateTimeRange(latestDate) {
      const latest = new Date(latestDate);
      const pastDate = new Date(latest);
      pastDate.setDate(latest.getDate() - 30);

      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      return [
        formatDate(pastDate),
        formatDate(latest)
      ];
    },

    getParameters(){
      this.$axios.get(this.$httpUrlVisualization+'/getParameters').then(res =>{
        res = res.data;
        if(res.code === 200){
          this.ParamData = []
          this.parseParameter(res.data);
        }else{
          this.$message.error(res.msg);
        }
      })
    },

    parseParameter(param){
      for(let i=0;i<param.length;i++){
        this.ParamData.push({
          label: param[i].parameter_mean,
          key: param[i].parameter_id
        })
      }
      sessionStorage.setItem('ParamData', JSON.stringify(this.ParamData))
    },

    parseSeriesData(seriesData) {
      const series = [];
      for(const key in seriesData) {
        series.push({
          name: key,
          type: 'line',
          data: seriesData[key],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              { type: 'min', name: 'Min' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          }
        })
      }
      return series;
    },

    loadDataOfParallel(){
      const input = {
        startTime: this.timeRange[0],
        endTime: this.timeRange[1],
        parameters: this.ShowParam
      }

      this.$axios.post(this.$httpUrlVisualization+'/getParallelData',input).then(res =>{
        res = res.data
        if(res.code === 200){
          this.optionsSideWall.xAxis.data = res.data.XData;
          console.log(res.data.seriesData)
          const newSeriesData = this.scaleSeriesData(res.data.seriesData);
          this.optionsSideWall.series = this.parseSeriesData(newSeriesData);
          this.chartSideWall.setOption(this.optionsSideWall);
          this.handleResize(); // 数据加载完成后重新调整大小
        }else{
          this.$message.error(res.msg);
        }
      })
    },

    confirmPrint(){
      if(this.timeRange === null) {
        this.$message.error('请选择时间范围');
        return;
      }
      this.isLoading = true;
      if (this.chartSideWall) {
        this.chartSideWall.dispose();
      }
      this.initChartSideWall();
      this.loadDataOfParallel();
      setTimeout(() => {
        this.isLoading = false;
      },500)
    },

    showParameter(){
      this.DialogTimePick = true;
    },

    initChartSideWall() {
      this.chartSideWall = echarts.init(document.getElementById('line'));
      this.optionsSideWall = {
        title: {
          text: '参数历史趋势图',
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          confine: true // 确保提示框在容器内
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          top: 40,
          left: 'center',
          width: '90%',
          padding: [5, 10],
          itemGap: 10,
          itemWidth: 25,
          itemHeight: 14,
          textStyle: {
            width: 120,
            overflow: 'truncate',
            ellipsis: '...'
          }
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            magicType: { type: ['line', 'bar'] },
            saveAsImage: {
              pixelRatio: 2 // 提高保存图片的质量
            }
          },
          right: 20,
          top: 10
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: null,
          axisLabel: {
            rotate: 30, // 标签旋转角度
            interval: 'auto' // 自动计算显示间隔
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100,
            handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleSize: '80%',
            handleStyle: {
              color: '#fff',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2
            }
          }
        ],
        series: []
      };
      this.chartSideWall.setOption(this.optionsSideWall);
    },

    getLatestTimeDay(){
      this.$axios.get(this.$httpUrlVisualization+'/getLatestTimeDay').then(res =>{
        res = res.data
        if(res.code === 200){
          const latestDate = res.data.latestTime_day
          sessionStorage.setItem('latestTime_day',latestDate)
          this.timeRange = this.updateTimeRange(latestDate)
          this.initChartSideWall();
          this.loadDataOfParallel()
        }else{
          this.$message.error(res.msg)
        }
      })
    },

    handleResize() {
      if (this.chartSideWall) {
        this.chartSideWall.resize();
      }
    }
  },
  mounted() {
    if (sessionStorage.getItem('ParamData')) {
      this.ParamData = JSON.parse(sessionStorage.getItem('ParamData'))
    } else {
      this.getParameters()
    }

    this.getLatestTimeDay()
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartSideWall) {
      this.chartSideWall.dispose();
    }
  }
}
</script>

<style scoped>
.headPart {
  align-items: center;
  justify-content: center;
  padding: 12px 0 0 18px;
  border-radius: 15px;
  box-shadow: 0 2px 8px 2px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

/* 优化后的chartPart样式 */
.chartPart {
  margin: 10px; /* 减少边界距离 */
  padding: 15px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 200px); /* 增加顶部空间 */
  width: calc(100% - 50px); /* 减少宽度 */
  overflow: hidden; /* 防止内容溢出 */
}

@media (max-width: 768px) {
  .chartPart {
    margin: 8px;
    padding: 10px;
    height: calc(100vh - 180px);
    width: calc(100% - 16px);
    border-radius: 12px;
  }
}

#line {
  height: 100%;
  width: 100%;
}
</style>
